import 'dart:convert';

import 'package:http/http.dart' as http;

import '../models/product.dart';
import 'auth_service.dart';

class ProductService {
  static const String _baseUrl = 'http://127.0.0.1:3000/api';
  final AuthService _authService;

  ProductService(this._authService);

  Future<List<Product>> getProducts({
    String? category,
    String? search,
    int page = 1,
    int limit = 20,
  }) async {
    try {
      final queryParams = {
        'page': page.toString(),
        'per_page': limit.toString(),
        if (category != null) 'category': category,
        if (search != null) 'search': search,
      };

      final uri = Uri.parse('$_baseUrl/products').replace(queryParameters: queryParams);
      final response = await http.get(
        uri,
        headers: {
          'Content-Type': 'application/json',
          if (_authService.token != null) 'Authorization': 'Bearer ${_authService.token}',
        },
      );

      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        return (data['products'] as List).map((json) => Product.fromJson(json)).toList();
      }
      return [];
    } catch (e) {
      print('获取商品列表失败: $e');
      return [];
    }
  }

  Future<Product?> getProductById(String id) async {
    try {
      final response = await http.get(
        Uri.parse('$_baseUrl/products/$id'),
        headers: {
          'Content-Type': 'application/json',
          if (_authService.token != null) 'Authorization': 'Bearer ${_authService.token}',
        },
      );

      if (response.statusCode == 200) {
        return Product.fromJson(jsonDecode(response.body));
      }
      return null;
    } catch (e) {
      print('获取商品详情失败: $e');
      return null;
    }
  }

  Future<List<String>> getCategories() async {
    try {
      final response = await http.get(
        Uri.parse('$_baseUrl/products/categories'),
        headers: {
          'Content-Type': 'application/json',
          if (_authService.token != null) 'Authorization': 'Bearer ${_authService.token}',
        },
      );

      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        return (data['categories'] as List).cast<String>();
      }
      return [];
    } catch (e) {
      print('获取分类列表失败: $e');
      return [];
    }
  }

  Future<Product?> createProduct({
    required String name,
    required String description,
    required double price,
    required String imageUrl,
    required int stock,
    required String category,
    double? discount,
  }) async {
    try {
      final response = await http.post(
        Uri.parse('$_baseUrl/products'),
        headers: {
          'Content-Type': 'application/json',
          if (_authService.token != null) 'Authorization': 'Bearer ${_authService.token}',
        },
        body: jsonEncode({
          'name': name,
          'description': description,
          'price': price,
          'imageUrl': imageUrl,
          'stock': stock,
          'category': category,
          if (discount != null) 'discount': discount,
        }),
      );

      print('创建商品响应状态码: ${response.statusCode}');
      print('创建商品响应内容: ${response.body}');

      if (response.statusCode == 201) {
        return Product.fromJson(jsonDecode(response.body));
      }
      return null;
    } catch (e) {
      print('创建商品失败: $e');
      return null;
    }
  }

  Future<Product?> updateProduct({
    required String id,
    required String name,
    required String description,
    required double price,
    required String imageUrl,
    required int stock,
    required String category,
    double? discount,
  }) async {
    try {
      final response = await http.put(
        Uri.parse('$_baseUrl/products/$id'),
        headers: {
          'Content-Type': 'application/json',
          if (_authService.token != null) 'Authorization': 'Bearer ${_authService.token}',
        },
        body: jsonEncode({
          'name': name,
          'description': description,
          'price': price,
          'imageUrl': imageUrl,
          'stock': stock,
          'category': category,
          if (discount != null) 'discount': discount,
        }),
      );

      print('更新商品响应状态码: ${response.statusCode}');
      print('更新商品响应内容: ${response.body}');

      if (response.statusCode == 200) {
        return Product.fromJson(jsonDecode(response.body));
      }
      return null;
    } catch (e) {
      print('更新商品失败: $e');
      return null;
    }
  }

  Future<bool> deleteProduct(String id) async {
    try {
      final response = await http.delete(
        Uri.parse('$_baseUrl/products/$id'),
        headers: {
          'Content-Type': 'application/json',
          if (_authService.token != null) 'Authorization': 'Bearer ${_authService.token}',
        },
      );

      print('删除商品响应状态码: ${response.statusCode}');
      return response.statusCode == 200;
    } catch (e) {
      print('删除商品失败: $e');
      return false;
    }
  }
}
